<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图片类型判断</title>
</head>

<body>

    <input type="file" id="your-files" multiple>

    <script src="https://cdn.bootcss.com/jquery/1.12.0/jquery.min.js"></script>
    <script>

        function returnTypeHeader(file,callback){
            var blob = file; // See step 1 above
            var fileReader = new FileReader();
            fileReader.onloadend = function(e) {
                var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
                var header = "";
                for(var i = 0; i < arr.length; i++) {
                    header += arr[i].toString(16);
                }
                
                //获取到的header信息
                //console.log(header);

                //判断类型
                switch (header) {
                    case "89504e47":
                        type = "image/png";
                        break;
                    case "47494638":
                        type = "image/gif";
                        break;
                    case "ffd8ffe0":
                    case "ffd8ffe1":
                    case "ffd8ffe2":
                    case "ffd8ffe3":
                    case "ffd8ffe8":
                        type = "image/jpeg";
                        break;
                    default:
                        type = "unknown"; // Or you can use the blob.type as fallback
                        break;
                }

                if(callback){
                    callback(type);
                }

            };
            fileReader.readAsArrayBuffer(blob);
        }


        //demo
        if (window.FileReader && window.Blob) {
            var control = document.getElementById("your-files");
            control.addEventListener("change", function(event) {
                // When the control has changed, there are new files
                var files = control.files;
                for(var i = 0; i < files.length; i++) {
                    //获取其他信息
                    // console.log("Filename: " + files[i].name);
                    // console.log("Type: " + files[i].type);
                    // console.log("Size: " + files[i].size + " bytes");

                    returnTypeHeader(files[i],function(type){
                        //打印出检测到的类型
                        console.log(type);

                        //获取到的真正的image类型
                        if(type != "unknown"){
                            alert("正确");
                        }else{
                            alert("失败");
                        }
                    });

                }
            }, false);
        } else {
            alert("您的浏览器太老了，请升级最新浏览器使用上传功能");
        }
        
    </script>
</body>

</html>